<?php

namespace app\admin\model;

use addons\epay\library\Service;
use think\Model;


class Refund extends Model
{

    

    

    // 表名
    protected $name = 'refund';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'status_text'
    ];
    public function getOriginData()
    {
        return $this->origin;
    }

    
    public static function init()
    {
        self::afterUpdate(function($row){
            $changed = $row->getChangedData();//修改的数据
            $origin = $row->getOriginData();//原始数据
            $detail = Order::find($origin['order_id']);
            if($detail) {
                $detail->status = $changed['status'] == 1 ? 5 : 6;
                $detail->save();
            }
      
            if($changed['status'] == 1) {//如果同意
                Service::refund($detail->order_id,$detail->pay_money,date('YmdHis').rand(1000,9999));
            }
        });
        
    }

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


}
